import React from 'react';
import { Input, Icon, Modal } from 'antd';
import { Map, Marker } from 'react-amap';
import SearchBox from '@/components/AMap/SearchBox';

const MapIcon = <Icon type="environment" />;

const style = {
  padding: 0,
  height: 500,
  width: 700,
};

export default class MapInput extends React.Component {
  static defaultProps = {
    mapProps: {},
    bodyStyle: style,
    onOk: () => {},
    onCancel: () => {},
    onClick: () => {},
  };

  static getDerivedStateFromProps(nextProps, preStates) {
    if ('value' in nextProps) {
      const { value } = nextProps;
      let { position } = preStates;
      // value改变或者定位删除（通过setFieldValue进行操作时）修改position数据
      if (value !== preStates.value || position === undefined) {
        if (value) {
          const lnglat = value.split(',');
          position = { lng: Number(lnglat[0]), lat: Number(lnglat[1]) };
        } else {
          position = null;
        }
      }
      return {
        value,
        position,
      };
    }
    return null;
  }

  constructor(props) {
    super(props);
    const { value } = props;
    this.amapEvents = {
      created: ins => {},
      click: e => {
        const { lnglat } = e;
        this.setState({
          position: lnglat,
        });
      },
    };

    let position;
    if (value) {
      const lnglat = value.split(',');
      position = { lng: Number(lnglat[0]), lat: Number(lnglat[1]) };
    }
    this.state = {
      visible: false,
      position: position || null,
      value,
    };
  }

  handleClick = e => {
    const { onClick } = this.props;
    const promise = onClick(e);
    if (promise === false) return null;
    if (promise instanceof Promise) {
      return promise.then(() => {
        this.setState({
          visible: true,
        });
      });
    }
    this.setState({
      visible: true,
    });
    return null;
  };

  handleOk = e => {
    const { onOk } = this.props;
    const { position } = this.state;
    const promise = onOk(position, e);
    if (promise === false) return null;
    if (promise instanceof Promise) {
      return promise.then(() => {
        this.setState({
          visible: false,
          value: position.toString(),
        });
        this.triggerChange(position.toString());
      });
    }
    this.setState({
      visible: false,
      value: position.toString(),
    });
    this.triggerChange(position.toString());
    return null;
  };

  handleCancel = e => {
    const { onCancel } = this.props;
    const promise = onCancel(e);
    if (promise === false) return null;
    if (promise instanceof Promise) {
      return promise.then(() => {
        this.setState({
          visible: false,
          position: undefined,
        });
      });
    }
    this.setState({
      visible: false,
      position: undefined,
    });
    return null;
  };

  handleSelect = res =>
    new Promise(resolve => {
      this.setState({
        position: res.location,
      });
      resolve();
    });

  handleChange = e => {
    this.setState({
      value: e.target.value,
      position: null,
    });
    this.triggerChange(e.target.value);
  };

  triggerChange = changedValue => {
    // Should provide an event to pass value to Form.
    const { onChange } = this.props;
    if (onChange) {
      onChange(changedValue);
    }
  };

  render() {
    const { mapProps, bodyStyle, onOk, onCancel, ...inputProps } = this.props;
    const { visible, position, value } = this.state;
    return (
      <React.Fragment>
        <Input
          addonBefore={MapIcon}
          {...inputProps}
          onClick={this.handleClick}
          value={value}
          onChange={this.handleChange}
          readOnly
          allowClear
        />
        <Modal
          visible={visible}
          bodyStyle={bodyStyle}
          width={bodyStyle.width}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          destroyOnClose
        >
          <Map zoom={15} {...mapProps} center={position} events={this.amapEvents}>
            {position && <Marker position={position} />}
            <SearchBox onSelect={this.handleSelect} />
          </Map>
        </Modal>
      </React.Fragment>
    );
  }
}
